const fs = require("fs");
const path = require("path");
const bencode = require('bencode');
const sha1 = require('js-sha1');
const moment = require('moment');
const { type } = require("os");

/**
 * 判断是否是指定字符串结尾
 */
function confirmEnding(str, target) {
   var start = str.length-target.length;
   var arr = str.substr(start,target.length);
   if(arr == target){
     return true;
   }
  return false;
 }

// 获取磁链链接，dirPath为文件夹路径
function readDir(dirPath) {
   //读取文件夹下面的文件名称列表，注意只有文件名称而不是全路径
   var fileslist = fs.readdirSync(dirPath);
   var magnetlist = new Array();
   for (var f in fileslist) {
      var filename = fileslist[f].toString();
      if (confirmEnding(filename,".torrent")) {
         var filepath = path.join(dirPath, filename);
         console.log('准备解析文件:' + filepath)
         var magnet = getInfoHash(filepath);
         if (magnet) {
            magnetlist.push(magnet);
         }
      }
   }
   return magnetlist;
}

// 获取磁链链接，fileslist为文件路径数组
function readFile(fileslist) {
   var magnetlist = new Array();
   fileslist.forEach(filepath => {
      if (confirmEnding(filepath,".torrent")) {
         console.log('准备解析文件:' + filepath)
         var magnet = getInfoHash(filepath);
         if (magnet) {
            magnetlist.push(magnet);
         }
      }
   });
   return magnetlist;
}



// 将结果输出为txt
function outMagnets2File(magnets, targetPath) {
   if (magnets.length > 0) {
      //使用set去重复
      var writebuffer = Buffer.from(arrayToString(new Set(magnets), '\n'));
      var dirPath = targetPath.toString();
      var dirName = path.basename(dirPath);
      var dirParentPath = path.dirname(dirPath);
      var savepath = path.join(dirParentPath, dirName + "-磁力链接-" + moment(Date.now()).format('YYYYMMDD-HHmmss') + ".txt");
      var writesteam = fs.createWriteStream(savepath);
      writesteam.write(writebuffer, 'utf-8');
      writesteam.end();
      writesteam.on('finish', function () {
         console.log("写入完成");
      });
      writesteam.on('error', function (err) {
         console.log(err);
      });
   }
}


//结果输出到剪切板
function outMagnets2CopyText(magnets) {
   var writeText = arrayToString(new Set(magnets), '\n')
   utools.copyText(writeText);
}

// buffer只能输出字符，所以必须将字符数组转换为字符形式，seq为分隔符
function arrayToString(arr, seq) {
   var str_value = null;
   for (a of arr) {
      var astr = a.toString();
      if (str_value) {
         str_value = str_value + seq + astr;
      } else {
         str_value = astr;
      }
   }
   return str_value;
}

// 获取种子文件的info_hash值，有一个解密，再加密的过程
function getInfoHash(torrentfile) {
   try {
      var result = bencode.decode(fs.readFileSync(torrentfile));
      if (result) {
         var info = result['info']; //info 字典
         var info_hash = sha1(bencode.encode(info));
         var magnet = "magnet:?xt=urn:btih:" + info_hash.toString();
         return magnet;
      }
   } catch (e) {
      console.log("错误:" + torrentfile)
   }
   return null;
}

window.exports = {
   "cmd_torrent2magnet_dir": { // 注意：键对应的是 plugin.json 中的 features.code
      mode: "none",  // 用于无需 UI 显示，执行一些简单的代码
      args: {
         // 进入插件应用时调用
         enter: (action) => {
            // 1.隐藏主界面
            window.utools.hideMainWindow()
            // 2. 获取复制的文件夹,返回 [{ isFile: true, isDirectory: false, name: 'test.png', path: '/path/to/test.png' }]
            var selectFile = utools.getCopyedFiles()[0]
            // 3. 把选中目录下bt文件转成磁力链接
            if (selectFile.isDirectory) {
               var dirPath = selectFile.path;
               outMagnets2File(readDir(dirPath), dirPath);
            }
            // 4.退出插件
            window.utools.outPlugin()
         }
      }
   },
   "cmd_torrent2magnet_file": { // 注意：键对应的是 plugin.json 中的 features.code
      mode: "none",  // 用于无需 UI 显示，执行一些简单的代码
      args: {
         // 进入插件应用时调用
         enter: (action) => {
            // 1.隐藏主界面
            window.utools.hideMainWindow()
            // 2. 获取复制的文件,返回 [{ isFile: true, isDirectory: false, name: 'test.png', path: '/path/to/test.png' }]
            var selectFiles = utools.getCopyedFiles();
            var filePaths = selectFiles.filter(it => it.isFile).map(it => it.path);
            // 3. 把选中bt文件转成磁力链接
            outMagnets2CopyText(readFile(filePaths));
            // 4.退出插件
            window.utools.outPlugin();
         }
      }
   }
}
